<template>
	<view class="wrapper">
		<NavbarModule :title="$t('index.contacts')" @showBubbleBox="showBubbleBox" :type="1"
			@handleSearch="gotoPage('/pagesTool/searchFriend/SearchFriend')" />
		<scroll-view scroll-top="0" scroll-y="true" class="scroll-Y"
			:style="`height: calc(${WindowInfo.windowHeight}px - 44px)`" :scroll-into-view="scrollIntoView">
			<view class="box">
				<view class="line" @click="handleToPage('/pages/friends/AddNewFriend')">
					<view class="iconfont icon-igw-f-contact-plus friends-icon"></view>
					<view class="text">{{ $t("contacts.New-Friends") }}</view>
				</view>
				<view class="line" @click="handleToPage('/pages/friends/GroupChatList')">
					<view class="iconfont icon-renyuan group-icon"></view>
					<view class="text">{{ $t("contacts.Group-Chats") }}</view>
				</view>
			</view>
			<view class="chat-content">
				<view v-for="(item, index) in list" :key="index">
					<view class="pinyin-line" :id="'s-' + (item.initial === '#' ? '0' : item.initial)">{{ item.initial }}</view>

					<view v-for="(item1, index1) in item.data" :key="index1" class="chat-line">
						<view class="chat-line__item" @click="
                handleToPage(
                  `/pages/chat/PersonalChat?targetId=${item1.userVo.userId}&commentName=${formatUserName(item1)}&friendId=${item1.friendId}`
                )
              ">
							<image v-if="isPeopleAvatarExit(item1.userVo.avatarCompress || item1.userVo.avatar)"
								:src="item1.userVo.avatarCompress || item1.userVo.avatar" class="avatar-image" mode="aspectFill">
							</image>
							<view v-else class="avatar-image avator-font-setting"
								:style="{ background: `${getDefaultColor(item1.userVo && item1.userVo.avatarColorCode)}`, fontSize: '30upx' }">
								{{ formatUserName(item1).slice(0, 1) }}
							</view>
							<text class="right-text omit">{{ formatUserName(item1) }}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="suspension-frame" v-if="list && list.length > 0">
			<view class="text" v-for="(item, index) in list" :key="index" @click="onLocation(item.initial)"
				:class="{ active: currentView == item.initial }">{{ item.initial }}</view>
		</view>
		<BubbleBox v-if="bubbleBoxVisiable">
			<view class="menu-box">
				<view class="menu-item" v-for="(item, index) in menuList" :key="index" @click="menuClick(item)">
					{{ item.label }}
				</view>
			</view>
		</BubbleBox>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex";
	import {
		queryFriendsList
	} from "@/services/friends";
	import NavbarModule from "../../components/NavbarModule.vue";
	import {
		formatUserInfo,
		getDefaultColor
	} from "@/utils/index";
	import BubbleBox from "@/components/BubbleBox.vue";
	export default {
		components: {
			NavbarModule,
			BubbleBox
		},
		name: "Friends",
		data() {
			return {
				inputContent: "",
				newFriendsCount: 0,
				bubbleBoxVisiable: false,
				currentView: "",
				scrollIntoView: "",
				WindowInfo: '',
				friendsListData: []
			};
		},
		computed: {
			...mapState(["friendsList","token"]),
			menuList() {
				return [{
						label: this.$t("discover.Dating"), // 约会
						url: "/pages/makefriends/MakeFriends",
						type: 1,
						typeName: "Dating",
					},
					{
						label: this.$t('discover.Offer-a-reward'),
						url: "/pagesDiscover/reward/RewardRelease",
						type: 2,
						typeName: "Reward",
					},
					{
						label: this.$t('user.Trading-Center'),
						url: "/pagesUser/bourse/release",
						type: 2,
						typeName: "Transaction",
					},
					{
						label: this.$t('discover.Recruitment'), // 招聘
						url: "/pagesDiscover/recruitment/RecruitmentRelease",
						type: 2,
						typeName: "Recruitment",
					},
					{
						label: this.$t('discover.information'),
						url: "/pagesDiscover/information/InfoRelease",
						type: 2,
						typeName: "Recruitment",
					},
				];
			},
			list() {
				const list = this.pySegSort(
					this.friendsListData.filter((o) => o.userVo != null).map(item => {
						item.formatUserName = this.formatUserName(item)
						return item
					})
				) || []

				this.currentView = list && list.length > 0 ? list[0].initial : '';
				return list
			}
		},
		methods: {
			getDefaultColor,
			...mapMutations(["SET_FRIEND_LIST"]),
			...mapActions(["changeFriendsInfo"]),
			menuClick(item) {
				if (this.token) {
					if (item.typeName === "Dating") {
						if (!this.$store.state.friendsInformation.userPersonalsId) {
							this.gotoPage('/pagesDiscover/friendsInformation/EditData')
						} else {
							this.gotoPage('/pagesDiscover/friendsInformation/FriendsInformation')
						}
						return
					}
					this.gotoPage(item.url, item.type)
				} else {
					uni.navigateTo({
						url: "/pages/login/Login",
					});
				}
			},
			onLocation(value) {
				console.log(value);
				this.scrollIntoView = "s-" + (value === "#" ? "0" : value);
				this.currentView = value;
				console.log(value);
			},
			// 气泡框显隐
			showBubbleBox() {
				this.bubbleBoxVisiable = !this.bubbleBoxVisiable;
			},
			gotoPage(url, type) {
				if (type == 1) {
					uni.switchTab({
						url,
					});
					return;
				}
				uni.navigateTo({
					url,
				});
			},
			handleToPage(url) {
				uni.navigateTo({
					url: url,
				});
			},
			// 好友列表
			async getFriendsList() {
				if (this.friendsList && this.friendsList.length > 0 && this.friendsListData.length < 1) {
					this.friendsListData = []
					let twoDArr = this.averageFn(this.friendsList);
					// 2. 定义一个函数，专门用来做赋值渲染（使用二维数组中的每一项）
					const use2DArrItem = async (page) => {
						// 4. 从第一项，取到最后一项
						if (page > twoDArr.length - 1) {
							const resp = await queryFriendsList({
								pageNum: 1,
								pageSize: 1000
							});
							if (!resp.success) return;
							this.friendsListData = resp.result.rows
							this.SET_FRIEND_LIST(this.friendsListData);
							console.log("每一项都获取完了");
							return;
						}
						// 5. 使用请求动画帧的方式
						requestAnimationFrame(() => {
							// 6. 取出一项，就拼接一项（concat也行）
							this.friendsListData = [...this.friendsListData, ...twoDArr[page]];
							// 7. 这一项搞定，继续下一项
							page = page + 1;
							// 8. 直至完毕（递归调用，注意结束条件）
							use2DArrItem(page);
						});
					};
					// 3. 从二维数组中的第一项，第一堆开始获取并渲染（数组的第一项即索引为0）
					await use2DArrItem(0);
				} else {
					this.friendsListData = this.friendsList
					const resp = await queryFriendsList({
						pageNum: 1,
						pageSize: 1000
					});
					if (!resp.success) return;
					this.friendsListData = resp.result.rows
					this.SET_FRIEND_LIST(this.friendsListData);
				}


				// .map((item) => {
				//   this.friendsInfo[item.friendId] = formatUserInfo(item);
				//   this.changeFriendsInfo(this.friendsInfo);
				//   return this.friendsInfo[item.friendId];
				// });
			},
			// 分组分批分堆函数（一堆分20个）
			averageFn(arr) {
				let i = 0; // 1. 从第0个开始截取
				let result = []; // 2. 定义结果，结果是二维数组
				while (i < arr.length) { // 6. 当索引等于或者大于总长度时，即截取完毕
					// 3. 从原始数组的第一项开始遍历
					result.push(arr.slice(i, i + 20)); // 4. 在原有十万条数据上，一次截取10个用于分堆
					i = i + 20; // 5. 这10条数据截取完，再截取下十条数据，以此类推
				}
				return result; // 7. 最后把结果丢出去即可
			}
		},
		onShow() {
			setTimeout(() => {
				this.WindowInfo = uni.getWindowInfo()
			}, 100)
			this.getFriendsList();
			this.bubbleBoxVisiable = false;
		},
	};
</script>

<style lang="scss" scoped>
	.omit {
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		line-clamp: 1;
		-webkit-box-orient: vertical;
		word-wrap: break-word;
		white-space: pre-wrap;
		word-break: break-word;
	}

	.wrapper {
		width: 100%;

		.navbar {
			.u-nav-slot {
				display: flex;
			}

			.icon-color {
				color: #61bdb2;
				font-size: 30upx;
			}

			.icon-margin {
				margin-left: 50upx;
			}
		}

		.box {
			background: #ffffff;
			box-sizing: border-box;
			padding: 0 30upx;

			&.box>view:nth-last-child(1) {
				border-bottom: none;
			}

			.line {
				width: 100%;
				height: 120upx;
				border-bottom: 2upx solid #f6f6f6;
				display: flex;
				align-items: center;

				.friends-icon {
					width: 80upx;
					height: 80upx;
					background: linear-gradient(0deg, #fd644f 0%, #f28e26 100%);
					border-radius: 50%;
					font-size: 38upx;
					color: #ffffff;
					text-align: center;
					line-height: 80upx;
				}

				.group-icon {
					width: 80upx;
					height: 80upx;
					background: linear-gradient(0deg, #61bd95 0%, #7cdbb1 100%);
					border-radius: 50%;
					font-size: 50upx;
					color: #ffffff;
					text-align: center;
					line-height: 80upx;
				}

				.avatar {
					width: 80upx;
					height: 80upx;
					border-radius: 50%;
					text-align: center;
					line-height: 80rpx;
					font-size: 30upx;
					font-weight: 400;
					color: #ffffff;
				}

				.text {
					margin-left: 30upx;
					font-size: 30upx;
					font-weight: 400;
					color: #000000;
				}
			}
		}

		.chat-content {
			background-color: #f6f6f6;

			.chat-line {
				background-color: #fff;
				padding: 0 30rpx;
				border-bottom: 2rpx solid #f6f6f6;

				&__item {
					height: 120rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
				}

				.avatar-image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					text-align: center;
					line-height: 80rpx;
					font-size: 30upx;
					font-weight: 400;
					color: #ffffff;
					margin-right: 30rpx;
				}

				.right-text {
					flex: 1;
					font-size: 30upx;
					font-weight: 400;
					color: #000000;
				}
			}
		}

		.pinyin-line {
			width: 100%;
			height: 66upx;
			box-sizing: border-box;
			padding: 0 30upx;
			font-size: 24upx;
			font-weight: 400;
			color: #878787;
			line-height: 66upx;
		}

		.suspension-frame {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 20upx;
			width: 40upx;
			background: rgba($color: #000000, $alpha: 0.4);
			border-radius: 20upx;
			box-sizing: border-box;
			padding: 12upx 0;
			text-align: center;

			.text {
				font-size: 22upx;
				font-weight: 400;
				color: #ffffff;
				margin: 6upx 0;

				&.active {
					margin: 6rpx auto;
					width: 34upx;
					// height: 34upx;
					background: #61bdb2;
					border-radius: 17upx;
				}
			}
		}

		.scroll-Y {
			// height: calc(100vh - 44px - 50px - var(--status-bar-height) - env(safe-area-inset-bottom));
		}
	}

	// 气泡框内容
	.menu-box {
		padding: 0 30rpx;

		.menu-item {
			height: 80rpx;
			background: #0d1918;
			box-shadow: inset 0px -2rpx 0px 0px rgba(255, 255, 255, 0.05);
			line-height: 80rpx;
			font-size: 28rpx;
			font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
			font-weight: 400;
			color: #ffffff;
			line-height: 80rpx;
		}
	}
</style>